#include <core/Object.h>

/*
extern void addGlobalRef();
extern void removeGlobalRef();
*/

#include <stdio.h>
#include <core/core.h>

#include <typeinfo>

//#define MEMORY_LEAK_DEBUGGING

namespace yam3d
{
namespace core
{
namespace
{
    class RefCounter
    {
    public:
        RefCounter()
            : refs(0)
        {
        }


        ~RefCounter()
        {
            if( refs != 0 )
            {
                LOG("Memory leak detected!");
#if defined(MEMORY_LEAK_DEBUGGING)
                for( int i=0; i<m_objects.size(); ++i )
                {
                    LOG(m_objectNames[i].toStdString().c_str());
                }
#endif
            }
            else
            {
                LOG("No memory leaks detected!");
            }
            assert( refs == 0 );
        }

        void add(Object* o, const char* const name)
        {
#if defined(MEMORY_LEAK_DEBUGGING)
            m_objects.push_back(o);
            m_objectNames.push_back(name);
#endif
            ++refs;
        }

        void release(Object* o)
        {
#if defined(MEMORY_LEAK_DEBUGGING)
            int index = m_objects.indexOf(o);
            m_objects.remove(index);
            m_objectNames.remove(index);
#endif
            --refs;
        }

    private:
#if defined(MEMORY_LEAK_DEBUGGING)
        core::vector<Object*> m_objects;
        core::vector<string> m_objectNames;
#endif
        int refs;
    };

    static RefCounter refs;
}

Object::Object(const char* const name)
: m_numOfRefs(0)
{
    refs.add(this,name);
}

Object::~Object()
{
    refs.release(this);
    if( this->m_numOfRefs != 0 )
    {
        assert_message( this->m_numOfRefs == 0, "Can not delete core::object, when it have references some where else" );
    }
}



}
}


